package com.youhui.weixin.websocket;

import com.youhui.weixin.common.MythConfig;
import com.youhui.weixin.common.exception.MythException;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket服务端.
 *
 * @author: huang
 * Date: 17-11-15
 */
@Log4j
@Component
@ServerEndpoint("/websocket/{id}")
public class WebsocketServer {

    private static Map<String, Session> connections = new HashMap<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        connections.put(id, session);
    }

    @OnMessage
    public void onMessage(String text){
        log.info("WebSocket连接数：" + connections.size());
        String[] s = text.split(MythConfig.SOCKET_MESSAGE);
        Session ses = connections.get(s[0]);
        try {
            ses.getBasicRemote().sendText(s[1]);
        } catch (IOException e) {
            MythException.recode("websocket服务器异常:"+e.getMessage(), e, WebsocketServer.class);
        }
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
        log.error(throwable.getMessage());
    }

    @OnClose
    public void onClosing() throws IOException {
        connections.remove(session);
        session.close();
    }

}
